package com.rocketmq.simple;

import com.rocketmq.JmsProperties;
import com.rocketmq.MessageDto;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 同步发送
 * @author: hw
 * @date: 2021/3/24 15:35
 */
@Component
public class SyncSend {

    @Autowired
    private JmsProperties jmsProperties;


    public SendResult asyncSend(MessageDto messageDto) {
        // 消息创建者组
        DefaultMQProducer producer = new DefaultMQProducer(jmsProperties.getSyncProducerGroup());
        // 重试机制 配置3次
        producer.setRetryTimesWhenSendAsyncFailed(3);
        // 添加服务器地址
        producer.setNamesrvAddr(jmsProperties.getServerAddr());
        // 启动Producer实例
        try {
            producer.start();
            Message msg = new Message(messageDto.getTopic(), messageDto.getTag(), messageDto.getMessageBody().getBytes());
            SendResult sendResult =  producer.send(msg);
            // 关闭Producer实例。
            producer.shutdown();
            return sendResult;
        } catch ( InterruptedException | MQBrokerException | MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
